package io;
/*version 1.1
 * bug 1: First input wrong data, second right,error happens, cannot read file
 * debug for bug 1
 */

/* version 1.2 on 5 Mar 2011
 * by Mike
 * separate openFile() from courseDataFromFile() to facilitate testing
 */

import ioProcessor.CourseInputProcessor;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class CourseInput
{
	public static FileInputStream courseInput;
	public static CourseInputProcessor cip;
	public static String cInput = "by_luck_value";
	
	static void openFile() {
		System.out.print("Please enter the path of the Course file: ");
		Scanner input = new Scanner(System.in);
		File courseFile = new File(input.next());
		try
		{
			courseInput = new FileInputStream(courseFile);
			System.out.println("File open.");
			//	fileExists = true;
		} catch (FileNotFoundException e)
		{
			System.out.println("File not found. " + e);		
			//	fileExists = false;
		}
	}

	public static void courseDataFromFile()
	{
		//	boolean fileExists = false;
		//	FileInputStream courseInput = null;
		
		while (courseInput==null) {
			openFile();
		}

		DataInputStream courseData = null;
		BufferedReader courseReader = null;

		courseData = new DataInputStream(courseInput);
		courseReader = new BufferedReader(new InputStreamReader(courseData));

		
		if (cip==null)
			cip = new CourseInputProcessor();
		try 
		{		
			while((cInput = courseReader.readLine()) != null)
			{
				cip.processCourseData(cInput);
			}
		}
		catch(IOException e)
		{
			System.out.println("Exception while reading the file " + e);
		}
		
		try{
			courseData.close();
			courseReader.close();
			courseInput.close();
		}
		catch(IOException e){
	    	System.err.println("Error: " + e.getMessage());
		}
	}	
}
